package com.share.schedule.xxl.schedule;

import com.alibaba.fastjson.JSON;
import com.share.common.utils.DateExtUtil;
import com.share.common.utils.DateUtil;
import com.share.common.utils.DingDingUtil;
import com.share.common.utils.HttpUtil;
import com.xxl.job.core.context.XxlJobHelper;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.time.Duration;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;

@Slf4j
@Component
public class EsDelIndexJob {
    private final static String ES_ROOT_URL = "http://es.snyq.ltd:9200";
    private String arr1[] = {"share_log_", "share_error_log_"};
//    private String arr2[] = {".monitoring-es-7-", ".monitoring-kibana-7-"};

    @XxlJob("callEs")
    public void callEs() throws Exception {
        List<String> list = new LinkedList<>();
        list.add(ES_ROOT_URL + "/" + "share_log_");
        list.add(ES_ROOT_URL + "/" + "share_error_log_");
        LocalDateTime start = LocalDateTime.now();

        //计算核心参数
        int beforeDay = 3;
        try {
            String jobParam = "0";//XxlJobHelper.getJobParam();
            log.info("接收到参数JobParam={}", jobParam);
            int a1 = Integer.parseInt(jobParam);
            if (a1 < 0 || a1 >= 10) {
                throw new RuntimeException("参数-不合规");
            }

            //覆盖参数
            beforeDay = a1;
        } catch (Exception e) {
            beforeDay = 3;
        }

        log.info("有效参数beforeDay={}", beforeDay);
        Date curDate = new Date();
        for (int i = beforeDay; i < 3 + beforeDay; i++) {
            Date tmpDate = DateExtUtil.addDay(curDate, 0 - i);
            String date1 = DateExtUtil.getDate(tmpDate);

            list.add(ES_ROOT_URL + "/" + arr1[0] + date1);
            list.add(ES_ROOT_URL + "/" + arr1[1] + date1);

//            String date2 = new StringBuffer(date1).insert(6, ".").insert(4, ".").toString();
//            list.add(ES_ROOT_URL + "/" + arr2[0] + date2);
//            list.add(ES_ROOT_URL + "/" + arr2[1] + date2);
        }

        //发起请求
        for (String url : list) {
            try {
                log.info("正在请求url={}", url);
                String res = HttpUtil.delete(url);
            } catch (Exception e) {
                log.error("请求异常url={}", url, e);
            }
        }

        String title = "删除es索引";
        String content = title + " " + DateUtil.getDateTime() + System.lineSeparator() + JSON.toJSONString(list);
        DingDingUtil.sendMdMsg(title, content);

        LocalDateTime end = LocalDateTime.now();
        String msg = "共耗时：{}毫秒";
        long costTime = Duration.between(start, end).toMillis();
        log.info(msg, costTime);
        XxlJobHelper.log(msg, costTime);
    }

    public static void main(String[] args) throws Exception {
        new EsDelIndexJob().callEs();
    }
}
